package com.llsydn.demo.guard;

import android.app.AlertDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import com.llsydn.hello.R;

/**
 * @author lilinshen
 * @title 360手机卫士
 * @description 请填写相关描述
 * @date 2018/9/21 15:32
 */
public class GuardsActivity extends AppCompatActivity {
    /**
     * 使用GridView+BaseApdater显示界面
     */
    private GridView gv_main;
    private GuardsAdapter adapter;
    String[] names = new String[]{"手机防盗", "通讯卫士", "软件管理", "流量管理", "进程管理", "手机杀毒", "缓存清理", "高级工具", "设置中心"};
    int[] icons = new int[]{R.drawable.widget01, R.drawable.widget02, R.drawable.widget03, R.drawable.widget04, R.drawable.widget05, R.drawable.widget06, R.drawable.widget07, R.drawable.widget08, R.drawable.widget09};

    private SharedPreferences sp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_guards);
        //初始化
        gv_main = findViewById(R.id.gv_main);
        adapter = new GuardsAdapter(this, names, icons);
        sp = getSharedPreferences("llsydn", Context.MODE_PRIVATE);
        //显示
        gv_main.setAdapter(adapter);
        //给gideView的item设置点击监听
        gv_main.setOnItemClickListener((parent, view, position, id) -> {
            //得到当前点击的名称
            String name = names[position];
            Toast.makeText(GuardsActivity.this, name, Toast.LENGTH_SHORT).show();
        });
        //给grideView的item设置长按点击监听
        gv_main.setOnItemLongClickListener((parent, view, position, id) -> {
            if (position == 0) {
                //当前显示的名称
                TextView textView = view.findViewById(R.id.tv_item_name);
                String name = textView.getText().toString();
                //为dialog准备一个输入框对象
                EditText editText = new EditText(this);
                editText.setHint(name);

                new AlertDialog.Builder(this)
                        .setTitle("修改名称")
                        .setView(editText)
                        .setPositiveButton("修改", (dialog, which) -> {
                            String newName = editText.getText().toString();
                            //界面更新
                            textView.setText(newName);
                            //将新名词保存到sp中
                            sp.edit().putString("NAME", newName).commit();
                        })
                        .setNegativeButton("取消", null)
                        .show();
            }

            return true;
        });


    }


}
